// 单选:选择 上下曲线

import React, { Component } from 'react';
import { Form, TreeSelect, message } from 'antd';
import './modal.css';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import { reqProcessOrgList,reqProcessWsList,reqProcessDrillList,reqProcessDocList,reqProcessCurveList } from '../../api';



class SelectCurveForm extends Component {
  
  static propTypes = {
    setForm: PropTypes.func.isRequired,
    setCurve: PropTypes.func.isRequired,
    setDoc: PropTypes.func.isRequired, 

  };

  formRef = React.createRef();      

  state = {
    value: undefined,
    curvesList:[],  // 选中文件，获取曲线集合
    treeData: [],    // 已进入页面先加载 组织   { id: 1, pId: 0, value: '1', title: '组织1' },
    doc_id:'',   // 获取当前曲线的所在文件，用来传给父组件
    doc_name:'',
    doc_type:'',
    drill_org_id:'', // 当前用户选中的组织id
    drill_ws_id:'',  // 当前用户选中的工区id
    drill_id:'' ,    // 当前用户选中的井id
  };

  getOrg = async() => {    // 页面加载时，获取组织信息    
    const org_pid = this.props.user.org.org_id;
    const result = await reqProcessOrgList(org_pid);
    console.log("获取组织",result) 
    if(result.code === 200){
      const orgList = result.data;
      const treeData = [];
      orgList.map((item) => {
        return treeData.push({id: item.org_id ,pId:'0', value: item.org_id, title: item.org_name, selectable: false, type: item.type})   // item.org_id
      })
      this.setState({
        treeData
      })
    }else{
      message.error(result.data);
    } 
  }

  genTreeNode = (nodePid,Node,isLeaf = false) => {  // 获取数据后，转换格式  3！！！！！！！
      return {
        id: Node.ws_id || Node.drill_id || Node.doc_id || Node.curve_id,
        pId: nodePid,
        value: Node.ws_id || Node.drill_id || Node.doc_id || Node.curve_id,
        title: Node.ws_name || Node.drill_id || Node.title || Node.curve_name,
        selectable: isLeaf ? true : false,
        type: Node.type,
        docType: Node.doc_type || '',
        isLeaf
      };   
  };

  onLoadData = async(treeNode) =>{    // 异步加载数据   2！！！！！！
    const type = treeNode.type;
    //console.log("load",treeNode,type,nodePid);
    if(type === "org"){          // 点击组织，获取工区
      const ws_pid = treeNode.id;
      this.setState({ drill_org_id: ws_pid})
      const result = await reqProcessWsList(ws_pid);
      if(result.code === 200){
        const wsList = result.data;
        new Promise(resolve => {
          setTimeout(() => {
            this.setState({       //渲染新增节点
              treeData: this.state.treeData.concat(
                wsList.map((item) => {
                  return this.genTreeNode(ws_pid,item);
                })  
              ),
            });
            resolve();
          }, 200);
        }); 
      }else {
        message.error(result.data);
      } 
    }else if(type === "ws"){                // 点击工区，获取井
      const drill_org_id = this.state.drill_org_id;
      const drill_ws_id = treeNode.id;
      this.setState({ drill_ws_id })
      const result = await reqProcessDrillList(drill_org_id,drill_ws_id);
      if(result.code === 200){
        const drillList = result.data;
        new Promise(resolve => {
          setTimeout(() => {
            this.setState({       //渲染新增节点
              treeData: this.state.treeData.concat(
                drillList.map((item) => {
                  return this.genTreeNode(drill_ws_id,item)
                })  
              ),
            });
            resolve();
          }, 200);
        });
      }else{
        message.error(result.data);
      }   
    }else if(type === "drill"){            // 点击井，获取文件
      const drill_id = treeNode.id;
      const org_id = this.state.drill_org_id;
      const ws_id = this.state.drill_ws_id;
      this.setState({ drill_id })
      const result = await reqProcessDocList(drill_id,org_id,ws_id);
      if(result.code === 200){
        var docList = []
        result.data.map((item) => {
          let item1 = {
            doc_id: item.doc_id,
            title: item.title,
            type: item.type,
            doc_type: item.doc_type,
          }
          docList.push(item1)
        })
        new Promise(resolve => {
          setTimeout(() => {
            this.setState({       //渲染新增节点
              treeData: this.state.treeData.concat(
                docList.map((item) => {
                  return this.genTreeNode(drill_id,item)
                })  
              ),
            });
            resolve();
          }, 200);
        });
      }
    }else if(type === "doc"){            // 点击文件，获取曲线   ????????
      const doc_id = treeNode.id;
      const doc_type = treeNode.docType;
      const drill_id = this.state.drill_id;   
      const org_id = this.state.drill_org_id;
      const ws_id = this.state.drill_ws_id;
      this.setState({
        doc_id: doc_id,
        doc_name: treeNode.title,
        doc_type: doc_type
      });
      const result = await reqProcessCurveList(doc_id,doc_type,drill_id,org_id,ws_id);   // 获取曲线列表
      console.log("根据文件id获取所有曲线列表result",result);
      if(result.code === 200){
        const curvesList = result.data;
        new Promise(resolve => {
          setTimeout(() => {
            this.setState({       //渲染新增节点
              treeData: this.state.treeData.concat(
                curvesList.map((item) => {
                  return this.genTreeNode(doc_id,item,true);
                })  
              ),
            });
            resolve();
          }, 200);
        });
        this.setState({ curvesList })
      }  
    }else{
      message.error("获取失败！");
    }
  }

  onChange = value => {  // 最后选中的曲线id  
    this.setState({ value });
    var curveInfo;
    this.state.curvesList.map((item) => {
      if(item.curve_id === value){
        curveInfo = item;
      }
    })
    this.props.setCurve(curveInfo); 
    this.props.setDoc({doc_id: this.state.doc_id , doc_name: this.state.doc_name, doc_type: this.state.doc_type })    
    //console.log("最终选择的曲线id",value,this.curveName,this.state.doc_id,this.state.doc_name);
  };

  componentWillMount(){  // 1、页面载入时，获取组织   
    this.getOrg();
  }
  componentDidMount() {
    this.props.setForm(this.formRef);
  }

  render() {
    const { treeData } = this.state;
    return (
      <Form 
        ref={this.formRef}   
        name="control-ref" 
        onFinish={this.onFinish}  
      >    
        <Form.Item 
          name="curve_id" 
          label="选择曲线" 
          rules={[{ required: true }]}
        >
          <TreeSelect
            treeDataSimpleMode  // 使用简单格式的treedata
            style={{ width: '100%' }}
            value={this.state.value}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder="请选择"
            onChange={this.onChange}    //选中树节点时调用此函数，最后一步，选中文件
            loadData={this.onLoadData}   // 异步加载数据
            treeData={treeData}
          />
        </Form.Item>
      </Form>
    );
  }
}

export default connect(
  state => ({user: state.user, }),
  {}
)(SelectCurveForm);